import 'dart:convert';
import 'dart:io';

import 'package:flutter_app_update/flutter_app_update.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/version_api.dart';
import 'package:sainbainu/common/enums/platform_type.dart';
import 'package:sainbainu/common/models/response/version_update_response.dart';
import 'package:sainbainu/common/repositories/version_repository.dart';
import 'package:sainbainu/common/services/storage.dart';
import 'package:sainbainu/common/utils/util.dart';
import 'package:sainbainu/common/values/constant.dart';
import 'package:sainbainu/common/values/storage_keys.dart';

class AppUpdateService extends GetxService {
  static AppUpdateService get to => Get.find();

  AppUpdateService();

  /// 显示更新弹窗
  final _showUpdate = false.obs;
  RxBool get showUpdate => _showUpdate;

  /// 服务器版本数据
  final _versionUpdateResponse = VersionUpdateResponse().obs;
  Rx<VersionUpdateResponse>? get versionUpdateResponse =>
      _versionUpdateResponse;

  late VersionRepository _versionRepository;

  /// 本地版本号
  Future<int> get localVersionCode async {
    return await AzhonAppUpdate.getVersionCode;
  }

  @override
  void onInit() {
    super.onInit();

    _versionRepository = VersionRepository(VersionApi());

    checkUpdate();

    AzhonAppUpdate.listener((map) {
      // 1、{"type":"start"}
      //  2、{"type":"downloading","max":14250715,"progress":14250715}
      //  3、{"type":"done","apk":"/xx/com.sainbainu.sainbainu/cache/xx.apk"}
      // 2、{"type":"error","exception":"Error: Http response code = 404"}
      print('⏬⏬⏬app update listener: ${jsonEncode(map)}');
    });
  }

  @override
  void onClose() {
    super.onClose();
    AzhonAppUpdate.dispose();
  }

  /// 检查更新
  checkUpdate() {
    var cancelTime = StorageService.to.getInt(
      StorageKeys.cancelVersionUpgradeTime,
    );
    var curretnTime = DateTime.now().millisecondsSinceEpoch;
    if (cancelTime == null ||
        curretnTime - cancelTime >= AppConstant.showVersionUpgradeTime) {
      getNewVersionData();
    }
  }

  /// 获取新版本数据
  getNewVersionData() async {
    _versionUpdateResponse.value = await _versionRepository.newVersion(
      Util.getCurrentPlatformType(),
    );
    checkVersion();
  }

  /// 检查版本号
  void checkVersion() async {
    int localVersionCode = await this.localVersionCode;
    int? serviceVersionCode = int.tryParse(
      _versionUpdateResponse.value.versionNo ?? '',
    );
    var canUpdate = Util.chechVersionCode(localVersionCode, serviceVersionCode);
    if (canUpdate) {
      _showUpdate.value = true;
    }
  }

  /// 确认更新
  void confirmUpdate() {
    UpdateModel model = UpdateModel(
      _versionUpdateResponse.value.appLink ?? '',
      "SainBainu-v${_versionUpdateResponse.value.versionName}.apk",
      "ic_launcher",
      'https://apps.apple.com/cn/app/抖音/id1142110895',
    );
    AzhonAppUpdate.update(model);
    // 非强制更新的话 关闭弹窗
    if (int.parse(_versionUpdateResponse.value.forceFlag ?? '') == 0) {
      Get.back();
    }
  }

  /// 拒绝更新
  void cancelUpdate() {
    Get.back();
    // 保存拒绝时间
    StorageService.to.setInt(
      StorageKeys.cancelVersionUpgradeTime,
      DateTime.now().millisecondsSinceEpoch,
    );
  }

  /// 取消下载
  void cancelDownload() {
    AzhonAppUpdate.cancel.then((value) {
      print('取消下载$value');
    });
  }
}
